package com.zxw.cloud.gateway.ab;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.alibaba.nacos.ribbon.NacosServer;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author zouxw
 */
@Slf4j
public class MetadataAwarePredicate extends DiscoveryEnabledPredicate{

    @Override
    protected boolean apply(NacosServer server) {

        final Map<String, String> metadata = server.getMetadata();
        String version = metadata.get("version");
        if (StringUtils.isBlank(version)) {
            log.info("nacos server tag is blank ,GrayMetadataAwarePredicate return true");
            return true;
        }

        if(null == ReactiveRequestContextHolder.getRequestHeaders()){
            log.info("RequestAttributes is null");
            return true;
        }

        Map<String,Object> headers = ReactiveRequestContextHolder.getRequestHeaders();
        // 判断请求中是否有版本
        String target = headers.get("version").toString();
        if (StringUtils.isBlank(target)) {
            log.info("request headers version is blank,GrayMetadataAwarePredicate return true");
            return true;
        }

        log.info("request headers version is ,nacos server tag is {}", target, version);
        return target.equals(version);
    }

}